<template>
  <div class="photo-viewer" v-if="visible" @click.self="closeViewer">
    <div class="viewer-header">
      <div class="viewer-title">{{ photo?.file_name }}</div>
      <div class="viewer-actions">
        <el-button type="text" @click="toggleFullscreen">
          <el-icon>
            <FullScreen v-if="!isFullscreen" />
            <Aim v-else />
          </el-icon>
        </el-button>
        <el-button type="text" @click="openInFolder">
          <el-icon><FolderOpened /></el-icon>
        </el-button>
        <el-button type="text" @click="closeViewer">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
    
    <div class="viewer-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="viewer-loading">
        <el-loading />
      </div>
      
      <!-- 照片显示 -->
      <div v-else-if="photo" class="viewer-image-container">
        <img 
          :src="imageUrl" 
          :alt="photo.file_name"
          class="viewer-image"
          @load="handleImageLoad"
          @error="handleImageError"
        />
      </div>
      
      <!-- 错误状态 -->
      <div v-else class="viewer-error">
        <el-result icon="error" title="加载失败" sub-title="无法加载照片">
          <template #extra>
            <el-button type="primary" @click="retryLoad">重试</el-button>
          </template>
        </el-result>
      </div>
    </div>
    
    <!-- 导航按钮 -->
    <div v-if="photo && hasNavigation" class="viewer-navigation">
      <el-button 
        type="primary" 
        circle 
        class="nav-button nav-prev"
        @click="navigatePrev"
        :disabled="!hasPrev"
      >
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <el-button 
        type="primary" 
        circle 
        class="nav-button nav-next"
        @click="navigateNext"
        :disabled="!hasNext"
      >
        <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 照片信息面板 -->
    <div v-if="photo && showInfo" class="viewer-info-panel">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <div class="info-section">
            <div class="info-item">
              <span class="info-label">文件名：</span>
              <span class="info-value">{{ photo.file_name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">文件大小：</span>
              <span class="info-value">{{ formatFileSize(photo.file_size) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">图片尺寸：</span>
              <span class="info-value">{{ photo.width }} × {{ photo.height }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">格式：</span>
              <span class="info-value">{{ photo.format }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">拍摄时间：</span>
              <span class="info-value">{{ formatDate(photo.captured_at) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ formatDate(photo.created_at) }}</span>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="EXIF信息" name="exif">
          <div class="info-section">
            <div class="info-item">
              <span class="info-label">相机品牌：</span>
              <span class="info-value">{{ photo.camera_make || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">相机型号：</span>
              <span class="info-value">{{ photo.camera_model || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">GPS位置：</span>
              <span class="info-value">
                {{ photo.latitude && photo.longitude ? 
                    `${photo.latitude.toFixed(6)}, ${photo.longitude.toFixed(6)}` : 
                    '未知' }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">海拔：</span>
              <span class="info-value">{{ photo.altitude ? `${photo.altitude}米` : '未知' }}</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 信息切换按钮 -->
    <el-button 
      type="primary" 
      circle 
      class="info-toggle"
      @click="toggleInfo"
      :title="showInfo ? '隐藏信息' : '显示信息'"
    >
      <el-icon><InfoFilled /></el-icon>
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { ElButton, ElIcon, ElLoading, ElResult, ElTabs, ElTabPane } from 'element-plus';
import { 
  FullScreen, Aim, FolderOpened, Close, ArrowLeft, ArrowRight, InfoFilled 
} from '@element-plus/icons-vue';
import type { Photo } from '../../types/photo';

// 导入全局类型
import '../../types/global'

interface Props {
  visible: boolean;
  photo?: Photo;
  photos?: Photo[];
  currentIndex?: number;
}

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'navigate', index: number): void;
}

const props = withDefaults(defineProps<Props>(), {
  photos: () => [],
  currentIndex: 0
});

const emit = defineEmits<Emits>();

// 组件状态
const loading = ref(false);
const isFullscreen = ref(false);
const showInfo = ref(false);
const activeTab = ref('basic');
const imageError = ref(false);

// 计算属性
const imageUrl = computed(() => {
  if (!props.photo) return '';
  return `file://${props.photo.file_path}`;
});

const hasNavigation = computed(() => {
  return props.photos.length > 1;
});

const hasPrev = computed(() => {
  return props.currentIndex > 0;
});

const hasNext = computed(() => {
  return props.currentIndex < props.photos.length - 1;
});

// 监听照片变化
watch(() => props.photo, () => {
  if (props.photo) {
    loading.value = true;
    imageError.value = false;
  }
});

// 处理图片加载完成
const handleImageLoad = () => {
  loading.value = false;
};

// 处理图片加载错误
const handleImageError = () => {
  loading.value = false;
  imageError.value = true;
};

// 重试加载
const retryLoad = () => {
  imageError.value = false;
  loading.value = true;
};

// 关闭查看器
const closeViewer = () => {
  emit('update:visible', false);
};

// 切换全屏
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
    isFullscreen.value = true;
  } else {
    document.exitFullscreen();
    isFullscreen.value = false;
  }
};

// 在文件夹中打开
const openInFolder = () => {
  if (props.photo) {
    // TODO: 实现在文件夹中打开
    console.log('在文件夹中打开:', props.photo.file_path);
  }
};

// 导航到上一张
const navigatePrev = () => {
  if (hasPrev.value) {
    emit('navigate', props.currentIndex - 1);
  }
};

// 导航到下一张
const navigateNext = () => {
  if (hasNext.value) {
    emit('navigate', props.currentIndex + 1);
  }
};

// 切换信息面板
const toggleInfo = () => {
  showInfo.value = !showInfo.value;
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (!props.visible) return;
  
  switch (event.key) {
    case 'Escape':
      closeViewer();
      break;
    case 'ArrowLeft':
      navigatePrev();
      break;
    case 'ArrowRight':
      navigateNext();
      break;
    case 'i':
    case 'I':
      toggleInfo();
      break;
    case 'f':
    case 'F':
      toggleFullscreen();
      break;
  }
};

// 添加键盘事件监听
onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
});

// 移除键盘事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});
</script>

<style scoped lang="scss">
.photo-viewer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  
  .viewer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    color: white;
    
    .viewer-title {
      font-size: 16px;
      font-weight: 500;
    }
    
    .viewer-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .viewer-content {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    
    .viewer-loading {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .viewer-image-container {
      max-width: 90%;
      max-height: 90%;
      overflow: auto;
      
      .viewer-image {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    }
    
    .viewer-error {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }
  
  .viewer-navigation {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    pointer-events: none;
    
    .nav-button {
      pointer-events: auto;
    }
  }
  
  .viewer-info-panel {
    position: absolute;
    right: 0;
    top: 60px;
    bottom: 0;
    width: 300px;
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    overflow-y: auto;
    transform: translateX(0);
    transition: transform 0.3s ease;
    
    .info-section {
      padding: 15px;
      
      .info-item {
        display: flex;
        margin-bottom: 10px;
        
        .info-label {
          flex: 0 0 80px;
          font-weight: 500;
        }
        
        .info-value {
          flex: 1;
          word-break: break-all;
        }
      }
    }
  }
  
  .info-toggle {
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .photo-viewer {
    .viewer-info-panel {
      width: 100%;
      top: auto;
      bottom: 0;
      height: 40%;
      transform: translateY(100%);
      
      &.show {
        transform: translateY(0);
      }
    }
  }
}
</style>